﻿Imports AjaxControlToolkit

Public Class Reviews
    Inherits System.Web.UI.Page

    Dim DBManager As DBManager = New DBManager()

    'To set masterpage 
    Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
        'Check if user is null
        If (Session("user") IsNot Nothing) Then
            'Retrieve userAcc details from session
            Dim userLoggedIn As userAcc = Session("user")
            'Check if user is admin, assign masterpage respectively
            If userLoggedIn.isAdmin Then
                Me.MasterPageFile = "~/MasterPage/Admin.Master"
            Else
                Me.MasterPageFile = "~/MasterPage/User.Master"
            End If
        Else
            'For anonymous users
            Me.MasterPageFile = "~/MasterPage/User.Master"
            'Enable this line to prevent anonymous users from entering this page
            ' Response.Redirect("~/Login.aspx")
        End If
    End Sub
    'This constant is to alternate between ascending and descending sort orders for the reviews listview
    'when diffSort is false, it means that the same sort by type has been clicked twice or more in a row
    Private Shared diffSort As Boolean

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If (Not Page.IsPostBack) Then
            'Set sort up/down images to be not visible
            imgDateAsc.Visible = False
            imgDateDesc.Visible = False
            imgHelpfulAsc.Visible = False
            imgHelpfulDesc.Visible = False
            imgRatingAsc.Visible = False
            imgRatingDesc.Visible = False
        End If

        'Check if user is null
        If (Session("user") IsNot Nothing) Then

            'Retrieve userAcc details from session
            Dim userLoggedIn As userAcc = Session("user")
            HiddenField1.Value = userLoggedIn.userID
            lbLoggedin.Visible = False
            pnlListview.Visible = True
        Else
            lbLoggedin.Visible = True
            HiddenField1.Value = 0
            pnlListview.Visible = False
        End If


    End Sub

    'For formatting each item as it is databound in the listview for reviews
    Protected Sub lvComments_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewItemEventArgs)

        Dim lblUserID As Label = e.Item.FindControl("user_IDLabel")
        Dim btnDelete As LinkButton = e.Item.FindControl("lbDeleteComment")


        Dim commenterUserID = lblUserID.Text
        Try
            If (commenterUserID = Me.Session("user").userID) Or Me.Session("user").isAdmin Then
                btnDelete.Visible = True
            Else
                btnDelete.Visible = False
            End If
        Catch ex As Exception
            'If user is not logged in
            btnDelete.Visible = False
        End Try

    End Sub

    Protected Sub lvComments_ItemCommand(ByVal sender As Object, ByVal e As ListViewCommandEventArgs)
        Try
            Select Case e.CommandName
                Case ("reportComment")
                    If (MsgBox("Report comment as offensive or inappropriate ?", MsgBoxStyle.OkCancel, "Report comment") = MsgBoxResult.Ok) Then
                        Dim commentID = e.CommandArgument
                        DBManager.addReportDashboard(3, "report comment", "Comment reported as offensive", commentID, 0)
                    End If
                Case ("deleteComment")
                    If (MsgBox("Are you sure you want to delete this review?", MsgBoxStyle.OkCancel, "Delete Comment") = MsgBoxResult.Ok) Then
                        Dim commentID = e.CommandArgument
                        DBManager.deleteComment(commentID)
                        lvReview.DataBind()
                    End If
            End Select
        Catch ex As Exception

        End Try

    End Sub

    'For formatting each item as it is databound in the listview for reviews
    Protected Sub ListView1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles lvReview.ItemDataBound

        'To set colour of the helpfulness label based on whether it is negative or positive
        Dim labelHelp As Label = e.Item.FindControl("helpfulnessLabel")
        Dim tempString As String = labelHelp.Text
        If tempString = "0" Then
            'if 0, black
            labelHelp.ForeColor = Drawing.Color.Black
        ElseIf tempString.Contains("-") Then
            'If negative, red
            labelHelp.ForeColor = System.Drawing.Color.Red

        Else
            'If positive , green
            labelHelp.ForeColor = System.Drawing.Color.Green
        End If
        'To set the star ratings
        'get all the numerical ratings from 1-5
        Dim ratingQuality As Label = e.Item.FindControl("rating_qualityLabel")
        Dim ratingValue As Label = e.Item.FindControl("rating_valueLabel")
        Dim ratingServices As Label = e.Item.FindControl("rating_serviceLabel")
        Dim ratingOverall As Label = e.Item.FindControl("rating_overallLabel")

        'get all the numerical ratings and multiply by 20
        ' 1 = 20% , 2 = 40% , 3 = 60% , 4 = 80% , 5 = 100%
        Dim ratingQualityValue = Convert.ToInt32(ratingQuality.Text.ToString()) * 20
        Dim ratingValueValue = Convert.ToInt32(ratingValue.Text.ToString()) * 20
        Dim ratingServiceValue = Convert.ToInt32(ratingServices.Text.ToString()) * 20
        Dim ratingOverallValue = Convert.ToDouble(ratingOverall.Text.ToString()) * 20

        'Try to get profile pictures of the reviewer
        Dim lblUserID As Label = e.Item.FindControl("user_IDLabel")
        Dim reviwerUserID = lblUserID.Text
        Dim profileImage As Image = e.Item.FindControl("imgProfile")
        Dim imageID = DBManager.getUserImage(Convert.ToInt32(reviwerUserID))

        'Set default user image 
        If imageID = 0 Then
            imageID = 3
        End If
        profileImage.ImageUrl = "IHttpHandler.ashx?id=" + imageID.ToString

        'now to set all the div for the star rating system to display correctly
        Dim ratingQualityStar As System.Web.UI.HtmlControls.HtmlGenericControl = e.Item.FindControl("ratingQualityStar")
        ratingQualityStar.Attributes.Add("style", "width:" + ratingQualityValue.ToString() + "%")
        Dim ratingValueStar As System.Web.UI.HtmlControls.HtmlGenericControl = e.Item.FindControl("ratingValueStar")
        ratingValueStar.Attributes.Add("style", "width:" + ratingValueValue.ToString() + "%")
        Dim ratingServiceStar As System.Web.UI.HtmlControls.HtmlGenericControl = e.Item.FindControl("ratingServiceStar")
        ratingServiceStar.Attributes.Add("style", "width:" + ratingServiceValue.ToString() + "%")
        Dim ratingOverallStar As System.Web.UI.HtmlControls.HtmlGenericControl = e.Item.FindControl("ratingOverallStar")
        ratingOverallStar.Attributes.Add("style", "width:" + ratingOverallValue.ToString() + "%")

        Dim labelReviewID As Label = e.Item.FindControl("review_IDLabel")
        Dim reviewID As String = labelReviewID.Text

        'Initialize old comments accordion
        Dim accordionOld As Accordion = e.Item.FindControl("accordionOldComments")
        Dim accordionOldPane As AccordionPane = accordionOld.Panes(0)
        Dim lblNumCommentsAcc As Label = accordionOldPane.FindControl("numCommentsLabel")
        Dim numComments = DBManager.getReviewNumComments(Convert.ToInt32(reviewID)).ToString
        If (numComments.Equals("0")) Then
            accordionOld.Visible = False
            accordionOld.Enabled = False
        Else
            accordionOld.Visible = True
            accordionOld.Enabled = True
            lblNumCommentsAcc.Text = "View " + numComments + " comments "

        End If

        'To configure the nested listview for comments
        Dim lvComments As ListView = accordionOldPane.FindControl("lvComments")

        Dim objComments As SqlDataSource = e.Item.FindControl("SqlDataSourceComments")
        Dim parameter As Parameter = objComments.SelectParameters(0)
        parameter.DefaultValue = reviewID
        lvComments.DataSourceID = objComments.ID
        lvComments.DataBind()

        'Disable helpful rating button if user is not logged in 
        'Disable submit button if user is not logged in  
        Dim accordion As Accordion = e.Item.FindControl("accordionNewComment")
        Dim lbHelpfulYes As LinkButton = e.Item.FindControl("lbHelpfulYes")
        Dim lbHelpfulNo As LinkButton = e.Item.FindControl("lbHelpfulNo")

        Dim accordionCommentPane As AccordionPane = accordion.Panes(0)
        accordionCommentPane.Enabled = False
        Dim btnNewComment As Button = accordionCommentPane.FindControl("btnSubmitComment")
        Dim tbxNewComment As TextBox = accordionCommentPane.FindControl("tbxNewCommentText")
        Try
            If (Session("user") IsNot Nothing) Then
                accordionCommentPane.Enabled = True
                btnNewComment.ToolTip = "Submit new comment"
                tbxNewComment.ToolTip = ""
                lbHelpfulYes.Enabled = True
                lbHelpfulNo.Enabled = True
                lbHelpfulYes.ToolTip = "The review was helpful"
                lbHelpfulNo.ToolTip = "The review was not helpful"
            Else
                accordionCommentPane.Enabled = False
                btnNewComment.ToolTip = "Login to comment"
                tbxNewComment.ToolTip = "Login to comment"
                lbHelpfulYes.Enabled = False
                lbHelpfulNo.Enabled = False
                lbHelpfulYes.ToolTip = "Login to rate reviews"
                lbHelpfulNo.ToolTip = "Login to rate reviews"

            End If
        Catch ex As Exception

        End Try

    End Sub

    'For handling item commands in listview
    Protected Sub ListView1_ItemCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewCommandEventArgs) Handles lvReview.ItemCommand
        Dim lblReviewID As Label = e.Item.FindControl("review_IDLabel")
        Dim reviewID = lblReviewID.Text
        Dim lblUserID As Label = e.Item.FindControl("user_IDLabel")
        Dim userID = lblUserID.Text
        Dim lblReviewerID As Label = e.Item.FindControl("reviewer_IDLabel")
        Dim reviewerID = lblReviewerID.Text
        Dim lblHelpfulness As Label = e.Item.FindControl("helpfulnessLabel")
        Dim helpfulness = Convert.ToInt32(lblHelpfulness.Text)
        Try
            Select Case e.CommandName

                Case "helpfulYes"
                    If (
                    DBManager.addReviewRate(reviewID, Me.Session("user").userID, 1)) Then
                        helpfulness = helpfulness + 1
                        DBManager.updateReviewRating(reviewID, helpfulness)
                        lvReview.DataBind()
                    Else
                        MsgBox("Already rated this review", MsgBoxStyle.OkOnly, "Error")
                    End If

                Case ("helpfulNo")

                    If (DBManager.addReviewRate(reviewID, Me.Session("user").userID, -1)) Then
                        helpfulness = helpfulness - 1
                        DBManager.updateReviewRating(reviewID, helpfulness)
                        lvReview.DataBind()
                    Else
                        MsgBox("Already rated this review", MsgBoxStyle.OkOnly, "Error")
                    End If
                Case ("deleteReview")
                    If (MsgBox("Are you sure you want to delete this review?", MsgBoxStyle.OkCancel, "Delete Review") = MsgBoxResult.Ok) Then
                        DBManager.deleteReview(reviewID)
                        lvReview.DataBind()
                    End If

                Case ("reportReview")
                    If (MsgBox("Report review as offensive or inappropriate ?", MsgBoxStyle.OkCancel, "Report review") = MsgBoxResult.Ok) Then
                        DBManager.addReportDashboard(3, "report review", "Review reported as offensive", reviewID, 0)
                    End If

            End Select


        Catch ex As Exception

        End Try

    End Sub

    'Onload even of accordionOldComment
    Protected Sub accordionOldComment_Load(ByVal sender As Object, ByVal e As EventArgs)

        Dim x = Me.FindControl("accordionOldComment")
    End Sub

    'ItemCommand for accordionComment
    Protected Sub accordionComment_ItemCommand(ByVal sender As Object, ByVal e As AccordionCommandEventArgs)
        Try
            If e.CommandName = "newComment" Then
                'To get the accordion control
                Dim accordionParent As Accordion = e.Container.Parent.Parent
                'Using the ContentCssClass parameter to pass in the reviewID
                Dim combinedID = accordionParent.ContentCssClass
                Dim splitID = combinedID.Split("||")
                Dim user As userAcc = Session("user")
                Dim userID = user.userID
                Dim reviewID = splitID(2)

                Dim tbxCommentBody As TextBox = e.Container.FindControl("tbxNewCommentText")
                Dim comment = tbxCommentBody.Text
                DBManager.addReviewComment(reviewID, userID, comment)

                tbxCommentBody.Text = ""
                accordionParent.SelectedIndex = -1
                lvReview.DataBind()
            End If

        Catch ex As Exception

        End Try

        'Dim x As UpdatePanel = e.Item.FindControl("updatePanelListview")
    End Sub

    'Toggle sort by date button
    Protected Sub lbSortDate_Click(ByVal sender As Object, ByVal e As EventArgs) Handles lbSortDate.Click
        'Toggle between asc and desc
        If (hfSort.Value = "date") Then
            If (diffSort = True) Then
                hfAscDesc.Value = "desc"
                imgDateDesc.Visible = True
                imgDateAsc.Visible = False
                imgHelpfulAsc.Visible = False
                imgHelpfulDesc.Visible = False
                imgRatingAsc.Visible = False
                imgRatingDesc.Visible = False
                diffSort = False
            Else
                hfAscDesc.Value = "asc"
                imgDateAsc.Visible = True
                imgDateDesc.Visible = False
                imgHelpfulAsc.Visible = False
                imgHelpfulDesc.Visible = False
                imgRatingAsc.Visible = False
                imgRatingDesc.Visible = False
                diffSort = True
            End If


        Else
            hfAscDesc.Value = "desc"
            imgDateDesc.Visible = True
            imgDateAsc.Visible = False
            imgHelpfulAsc.Visible = False
            imgHelpfulDesc.Visible = False
            imgRatingAsc.Visible = False
            imgRatingDesc.Visible = False
        End If

        'Set sort to be by date
        hfSort.Value = "date"
    End Sub

    'Toggle sort by rating button
    Protected Sub lbSortRating_Click(ByVal sender As Object, ByVal e As EventArgs) Handles lbSortRating.Click
        'Toggle between asc and desc
        If (hfSort.Value = "rating") Then
            If (diffSort = True) Then
                hfAscDesc.Value = "desc"
                imgRatingDesc.Visible = True
                imgDateAsc.Visible = False
                imgDateDesc.Visible = False
                imgHelpfulAsc.Visible = False
                imgHelpfulDesc.Visible = False
                imgRatingAsc.Visible = False
                diffSort = False
            Else
                hfAscDesc.Value = "asc"
                imgRatingAsc.Visible = True
                imgDateAsc.Visible = False
                imgDateDesc.Visible = False
                imgHelpfulAsc.Visible = False
                imgHelpfulDesc.Visible = False
                imgRatingDesc.Visible = False
                diffSort = True
            End If

        Else
            hfAscDesc.Value = "desc"
            imgRatingDesc.Visible = True
            imgDateAsc.Visible = False
            imgDateDesc.Visible = False
            imgHelpfulAsc.Visible = False
            imgHelpfulDesc.Visible = False
            imgRatingAsc.Visible = False
        End If

        'Set sort to be by rating
        hfSort.Value = "rating"

    End Sub

    'Toggle sort by helpfulness
    Protected Sub lbSortHelpful_Click(ByVal sender As Object, ByVal e As EventArgs) Handles lbSortHelpful.Click
        'Toggle between asc and desc
        If (hfSort.Value = "helpfulness") Then
            If (diffSort = True) Then
                hfAscDesc.Value = "desc"
                imgHelpfulDesc.Visible = True
                imgDateAsc.Visible = False
                imgDateDesc.Visible = False
                imgHelpfulAsc.Visible = False
                imgRatingAsc.Visible = False
                imgRatingDesc.Visible = False
                diffSort = False
            Else
                hfAscDesc.Value = "asc"
                imgHelpfulAsc.Visible = True
                imgDateAsc.Visible = False
                imgDateDesc.Visible = False
                imgHelpfulDesc.Visible = False
                imgRatingAsc.Visible = False
                imgRatingDesc.Visible = False
                diffSort = True
            End If

        Else
            hfAscDesc.Value = "desc"
            imgHelpfulDesc.Visible = True
            imgDateAsc.Visible = False
            imgDateDesc.Visible = False
            imgHelpfulAsc.Visible = False
            imgRatingAsc.Visible = False
            imgRatingDesc.Visible = False
        End If

        'Set sort to be by rating
        hfSort.Value = "helpfulness"

    End Sub

End Class